package cz.idsv.web.mvc.model.dao;

import java.util.Collection;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cz.idsv.web.mvc.model.entity.AddressEntity;


/**
 * Address DAO implementation.
 * 
 * @author Jan Borzensky
 */

@Repository("AddressDaoImpl")
@Transactional(readOnly = true)
public class AddressDaoImpl implements AddressDao {

	protected HibernateTemplate template = null;

	/**
	 * Sets Hibernate session factory.
	 */
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		template = new HibernateTemplate(sessionFactory);
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public void save(AddressEntity addressEntity) {
		template.saveOrUpdate(addressEntity);
	}
	
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public void delete(AddressEntity addressEntity) {
		template.delete(addressEntity);
	}

	public AddressEntity findAddressById(Integer id) throws DataAccessException{
		return template.get(AddressEntity.class, id);
		
	
	}

	@SuppressWarnings("unchecked")
	public Collection<AddressEntity> findAddress() {
		return template.find("from Address");
	}

	@SuppressWarnings("unchecked")
	public Collection<AddressEntity> findAddressByStreet(String streetName)
			throws DataAccessException {
		return template.find("from Address a where a.street = ?", streetName);
	}

	@SuppressWarnings("unchecked")
	public Collection<AddressEntity> findAddressByCity(String cityName)
			throws DataAccessException {
		return template.find("from City a where a.city = ?", cityName);
		
	}

	@SuppressWarnings("unchecked")
	public Collection<AddressEntity> findAddressByStreetNumber(Integer streetNumber)
			throws DataAccessException {
		return template.find("from StreetNumber a where a.StreetNumber = ?", streetNumber);
		
	}

	@SuppressWarnings("unchecked")
	public Collection<AddressEntity> findAddressByPostNumber(Integer postNumber)
			throws DataAccessException {
		return template.find("from PostNumber a where a.PostNumber = ?", postNumber);
	}

}
